//
//  AddressBookCell.m
//  easyTaxi
//
//  Created by ellenpage on 12-12-18.
//  Copyright (c) 2012年 ellenpage. All rights reserved.
//

#import "AddressBookCell.h"
#import "Constant.h"
#import "GetPhoneInfo.h"

@interface AddressBookCell ()

@end

@implementation AddressBookCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [_nameTxtField canBecomeFirstResponder];
        _nameTxtField.userInteractionEnabled = NO;

    }
    return self;
}

+ (AddressBookCell *)getInstance
{
    return [[[NSBundle mainBundle] loadNibNamed:@"AddressBookCell" owner:self options:nil] objectAtIndex:0];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
}

- (IBAction)resignKeyboard
{
    [_nameTxtField resignFirstResponder];
}

- (IBAction)changeThisName:(UIButton *)sender
{
    _nameTxtField.userInteractionEnabled = YES;
    [_nameTxtField setDelegate:self];
    int i = sender.tag;
    _nameTxtField.tag = i;
    NSLog(@"t:%@", _nameTxtField);
    [_nameTxtField becomeFirstResponder];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    int i = textField.tag;
    
    NSMutableDictionary *dict =[NSMutableDictionary dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults]objectForKey:kMyAddressBook]];
    
    NSArray        *array  = [dict objectForKey:kAddressBookArray];
    NSMutableArray *mArray = [NSMutableArray arrayWithArray:array];
    
    NSMutableDictionary *tmpDict = [mArray objectAtIndex:i];
    NSString *str = [tmpDict objectForKey:kAddressName];
    if (![str isEqualToString:_nameTxtField.text])
    {
        if ([_nameTxtField.text length] > 0)
        {
            [tmpDict setObject:_nameTxtField.text forKey:kAddressName];
        }
        else
        {
            [tmpDict setObject:_nameTxtField.text forKey:kAddressName];
        }
        NSString *time = [GetPhoneInfo getCurrentTimeStamp];
        [dict setObject:time forKey:kAddressBookTimeStamp];
        
        [[NSUserDefaults standardUserDefaults] setObject:dict forKey:kMyAddressBook];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"])
    {
        _nameTxtField.userInteractionEnabled = NO;
        [_nameTxtField resignFirstResponder];
        return NO;
    }
    return YES;
}


@end
